package com.example.demo.auth;

import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 说明：
 *
 * @author 张垚
 * @since 2025/5/7 22:31
 */
@WebFilter(filterName = "authFilter", urlPatterns = "/*")
public class AuthFilter implements Filter {

    @Autowired
    private IAuthService authService;

    List<String> excludeUrls = new ArrayList<>();

    @PostConstruct
    public void init() {
        // 配置不需要进行token认证的地址
        excludeUrls.add("/login");
        excludeUrls.add("/register");
        excludeUrls.add("/logout");
        excludeUrls.add("/swagger");
        excludeUrls.add("/v2/api-docs");
        excludeUrls.add("/webjars");
        excludeUrls.add("/swagger-resources");
        excludeUrls.add("/doc.html");
        excludeUrls.add("/favicon.ico");
        excludeUrls.add("/error");
        // 添加其他需要排除的URL
        excludeUrls.add("/auth");
        // 文件接口
        excludeUrls.add("/file");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 获取request
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // 获取请求的URL
        String requestUri = request.getRequestURI();
        // 检查请求是否需要排除
        for (String excludeUrl : excludeUrls) {
            if (requestUri.contains(excludeUrl)) {
                // 如果请求需要排除，继续执行请求
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        // 从请求头中获取token
        String token = request.getHeader("token");
        // 检查token是否有效
        if (authService.getLoginUser() != null) {
            // 如果token有效，继续执行请求
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}